#include <cserver/restapi.h>
#include <cserver/uri.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <pqxx/transaction.hxx>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/hydrant/list";


	void hydrant_list(Request& req, pqxx::connection& dbconn, SessionContext& , const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& pattern = query["pattern"];
		pattern.insert(pattern.begin(), '%');
		pattern.push_back('%');
		auto& from_s = query["from"];
		auto& count_s = query["count"];
		bool issue_only = query.find("issueonly") != query.end();
		unsigned int from = from_s.empty() ? unsigned(0): boost::lexical_cast<unsigned>(from_s);
		unsigned int limit = count_s.empty() ? unsigned(2000): boost::lexical_cast<unsigned>(count_s);
		limit = std::min(limit, unsigned(2000));
		limit = std::max(limit, unsigned(1));

		StreamGroup sg(req);
		auto& fout = sg.fout;
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

		pqxx::work w(dbconn);
#if 1
		fout << boost::format(R"({"func":"hydrant/list",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":)") %  TotalCount(w, issue_only? "get_hydrant_issue_total" : "get_hydrant_total")(pattern).result();
#endif
		auto result = w.prepared(issue_only ? "get_hydrant_issue" : "get_hydrant")(pattern)(limit)(from).exec();
		fout << result2json(result, 3);
		fout << "}}";
		
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::hydrant_list);
}

